<?php 
namespace App\Http\Controllers\Home;

use Session;
use App\User;
use Validator;
use Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Home\ThrottlesLogins;
use Illuminate\Foundation\Home\AuthenticatesAndRegistersUsers;

header("content-type:text/html;charset=utf-8");
class MemberController extends Controller{
	private $goods_price = 0;
	//前台个人中心
	public function member(){
        if(Session::has('user_id','link')){
        	$user_id=Session::get('user_id');
            $link=Session::get('link');
        	$res=new \App\Member_Home();
        	$data=$res->find($user_id);

        }
		return view('Home/member',array('data'=>$data,'link'=>$link));
	}


    //编辑个人信息
    public function wen(){
        $req = request();
        if(Session::has('user_id')){
    	    $user_id=Session::get('user_id');
        }
    	if($_POST){
    		 $pic=str_random(3).$_FILES['user_photo']['name'];
			 $req->file('user_photo')->move('Home/photo',$pic);
			 $path = '/Home/photo/'.$pic;
    		$arr=array(
    			'user_name'=>$_POST['user_name'],
    			'user_photo'=>$path,
    			'user_password'=>md5($_POST['user_password']),
    			'user_email'=>$_POST['user_email'],
    			'user_tel'=>$_POST['user_tel']
    			);
    		// var_dump($_FILES);die;
            
			 $res=new \App\Member_Home();
			 $data=$res->add($arr,$user_id);
			 if($data){
			 	return "<script>alert('编辑成功！！');location.href='member'</script>";
			 }else{
			 	return "<script>alert('编辑失败！！');location.href='wen'</script>";
			 }
    	}else{

    		 $sql=new \App\Member_Home();
			 $date=$sql->find($user_id);
    	}
		return view('Home/Wen',array('date'=>$date));
	}

    //我的收货地址
	public function member_address(){
		if(Session::has('user_id','link')){
			$link=Session::get('link');
			if(Session::has('user_id')){
	    	    $user_id=Session::get('user_id');
	        }
	       
	        $res=new \App\Member_Home();
	        $ress=$res->select($user_id);
	        // var_dump($ress);die;
	        if($ress==null){
	           $row=1;
	        }else{
	           $row=$ress;
	        }
        }  
		return view('Home/member_address',array('ress'=>$row , 'link'=>$link));
	}

    
      //收货地址列表
	  public function is_show_list(){
       if(Session::has('user_id','link')){
			$link=Session::get('link');
		  	if(Session::has('user_id')){
	    	    $user_id=Session::get('user_id');
	        }
	        
	        $res=new \App\Member_Home();
	        $ressk=$res->selects($user_id);
	        // var_dump($ressk);die;
	        if($ressk==null){
	           $row=2;
	        }else{
	           $row=$ressk;
	        }
       }
		return view('Home/is_show_list',array('ressk'=>$row,'link'=>$link));
	}

    //设为默认收货地址
    public function is_show($address_id){
		
		if(Session::has('user_id')){
    	    $user_id=Session::get('user_id');
        }
            $res=new \App\Member_Home();
      
        	$is_show=$res->upshow($address_id);
	        $show=$res->upshow_a($address_id,$user_id);
	        if($is_show && $show){
	        	return redirect('home/member_address');
	        }else{
	        	return redirect('home/is_show_list');
	        }
         
    }


    //添加收货地址
    public function is_show_add(Request $req){
       if(Session::has('user_id','link')){
			$link=Session::get('link');    
	    	if($_POST){
	    		 //自动验证
	            $this->validate($req,[
	                'shen' => [
		                'required',
	                ],
	                'shi' => [
		                'required',
	                ],
		             'qu' => [
		                'required',
	                ],
	                'address_name' => [
		                'required',
	                ],
	                'address' => [
		                'required',
	                ],
	                'zipcode' => [
		                'required',
	                ],
	                'mobile' => [
		                'required',
	                ],
	              
	            ],
	                [
	                    'shen.required' => '（必填）',
	                    'shi.required' => '（必填）',
	                    'qu.required' => '（必填）',
	                    'address_name.required' => '（必填）',
	                    'address.required' => '（必填）',
	                    'zipcode.required' => '（必填）',
	                    'mobile.required' => '（必填）',
	                   
	                ]
	            );

	    		if(Session::has('user_id')){
	    	       $user_id=Session::get('user_id');
	            }
	            $shen=$_POST['shen'];
	            $shi=$_POST['shi'];
	            $qu=$_POST['qu'];
	            $res=new \App\Member_Home();
	    		$dats=$res->cha_s($shen);
	            $shens=$dats->region_name;
	    		$datw=$res->cha_w($shi);
	            $shis=$datw->region_name;
	            $date=$res->cha_e($qu);
	            $qus=$date->region_name;

	    		$arr=array(
	    			'shen'=>$shens,
	    			'shi'=>$shis,
	    			'qu'=>$qus,
	    			'address_name'=>$_POST['address_name'],
	    			'address'=>$_POST['address'],
	    			'zipcode'=>$_POST['zipcode'],
	    			'mobile'=>$_POST['mobile'],
	    			'acquiescence'=>1,
	    			'user_id'=>$user_id
	    			);
	            
	    		 $data=$res->insert($arr);
	              if($data){
	                 return "<script>alert('添加成功！！');location.href='is_show_list'</script>";
	              }else{
	              	return "<script>alert('添加失败！！');location.href='is_show_add'</script>";
	              }

	    	}else{
	    		 $res=new \App\Member_Home();
	    		 $data=$res->cha();

	    	}
        }
    	return view('Home/is_show_add',array('data'=>$data,'link'=>$link));
    }

    //修改收货地址
	public function is_show_update($address_id){
        if(Session::has('user_id','link')){
			$link=Session::get('link');
			if($_POST){
				$addid=$_POST['id'];

				$shen=$_POST['shen'];
	            $shi=$_POST['shi'];
	            $qu=$_POST['qu'];
	            $res=new \App\Member_Home();
	    		$dats=$res->cha_s($shen);
	            $shens=$dats->region_name;
	    		$datw=$res->cha_w($shi);
	            $shis=$datw->region_name;
	            $date=$res->cha_e($qu);
	            $qus=$date->region_name;

	        	$arr=array(
					'shen'=>$shens,
					'shi'=>$shis,
					'qu'=>$qus,
					'address_name'=>$_POST['address_name'],
					'address'=>$_POST['address'],
					'zipcode'=>$_POST['zipcode'],
					'mobile'=>$_POST['mobile'],
				);

				
				$sql=new \App\Member_Home();
				$date=$sql->update_save($arr,$addid);
				if($date){
					return "<script>alert('修改成功！！');location.href='http://www.nbshop.com/home/is_show_list'</script>";

				}else{
					return "<script>alert('修改失败！！');location.href='http://www.nbshop.com/home/is_show_update'</script>";
				}

			}else{
				 $res=new \App\Member_Home();
	    		 $data=$res->cha();
	    		 $arr=$res->cha_up($address_id);

			}
	    }
		return view('Home/is_show_update',array('data'=>$data,'arr'=>$arr,'link'=>$link));

	}


	//删除收货地址
	public function is_show_delete($address_id){
		$res=new \App\Member_Home();
		$data=$res->del($address_id);
		if($data){
            return "<script>alert('删除成功！！');location.href='http://www.nbshop.com/home/is_show_list'</script>";
		}else{
			return "<script>alert('删除失败！！');location.href='http://www.nbshop.com/home/is_show_delete'</script>";
		}
	}


    //三级联动子集
    public function getcity(){
		$id = $_GET['id'];
		// var_dump($id);
		//查询
		 $res=new \App\Member_Home();
         $citylist=$res->cha_a($id);
         // var_dump($citylist);
		echo json_encode($citylist);
	}

	public function member_cash(){
		return view('Home/member_cash');
	}
	//我的收藏
	public function member_collect(){
		if(Session::has('user_id','link')){
			$link=Session::get('link');
			$collect = new \App\Member_Home();
			$user_id = Session::get("user_id");
			$res = $collect->member_collect($user_id);
			$row = "";
			foreach($res as $key=>$val){
				$row[$key] = $val->goods_id;
			}
			$data = $collect->collect($row);
			$r = array_filter($data);
			if(empty($r)){
				$member_collect = 2;
			}else{
				$member_collect = $r;
			}
		}
		// print_r($member_collect);die;
		return view('Home/member_collect',["member_collect"=>$member_collect,"link"=>$link]);
	}
	//收藏删除
	public function collect_del($goods_id){
		$collect = new \App\Member_Home();
		$res = $collect->collect_del($goods_id);
		return redirect("home/member_collect");
	
	}
	//在收藏夹中添加购物车
	public function member_buycar($id){
		$buycar = new \App\Member_Home();
		$res = $buycar->buycarOnew($id);
		$arr = array(
			"goods_id"=>$res->goods_id,
			"goods_name"=>$res->goods_name,
			"goods_price"=>$res->goods_price
			);
		$data = $buycar->buycar_add($arr);
		if($data){
			return redirect('home/buycar');
		}else{
		 	echo '<script>alert("加入购物车失败");window.location.href="member_collect";</script>';
		}
	}



	public function member_commission(){
		return view('Home/member_commission');
	}
	public function member_links(){
		return view('Home/member_links');
	}
	public function member_member(){
		return view('Home/member_member');
	}
	public function member_member_list(){
		return view('Home/member_member_list');
	}
	public function member_money(){
		return view('Home/member_money');
	}
	public function member_money_charge(){
		return view('Home/member_money_charge');
	}
	public function member_money_pay(){
		return view('Home/member_money_pay');
	}
	public function member_msg(){
		return view('Home/member_msg');
	}
	public function member_order(){
		return view('Home/member_order');
	}
	public function member_packet(){
		return view('Home/member_packet');
	}
	public function member_results(){
		return view('Home/member_results');
	}
	public function member_safe(){
		return view('Home/member_safe');
	}
	public function member_user(){
		return view('Home/member_user');
	}
	/*
	购物车展示
	 */
	public function buycar(){
		if(Session::has('user_id') && Session::has('user_name')){
			$user_id = session::get('user_id');
			$Cart_Home= new \App\Cart_Home();
			$res=$Cart_Home->lists($user_id);
			if(empty($res)){
				echo '<script>alert("您还没有添加商品，赶快去选择自己心仪的商品吧！！！");window.history.back()</script>';
			}else{
				//所选商品总价
				$sum = array_sum(array_column($res,'goods_sum_price'));
				return view('Home/buycar',['res'=>$res,'sum'=>$sum]);
			}
		}else{
			echo '<script>alert("您还没登录,请先登录！！！");window.location.href="/home/login"</script>';
		}
	}
	public function cartdel($cart_id){
		$Cart_Home= new \App\Cart_Home();
		$cart_res=$Cart_Home->cart_del($cart_id);
		if($cart_res){
			echo '<script>alert("删除成功！！！");window.location.href="/home/buycar"</script>';
		}else{
			echo '<script>alert("删除失败！！！");window.location.href="/home/buycar"</script>';
		}
	}
	/**
	 * 验证商品库存，价格
	 * @param  [type] $goods_id [description]
	 * @return [type]           [description]
	 */
	public function checkNumber($goods_id,$cart_id,$buy_number,$product_attr){
		$product= new \App\product();
		$user_id = session::get('user_id');
		$number=$product->getNumber($goods_id,$product_attr);
		// echo $number[0]['product_number'];
		if($buy_number>$number[0]['product_number']){
			echo -1;
		}else{
			$Cart_Home= new \App\Cart_Home();
			//更改购物车物品数量
			$res=$Cart_Home->addNumber($goods_id,$buy_number,$cart_id,$user_id);
			//根据购物车自增id和商品id 查询出当前的单价
			$price=$Cart_Home->getprice($goods_id,$cart_id,$user_id);
			$price=$price[0]['goods_price'];
			//当前单价*$buy_number 获取当前总价
			$price_sum=$buy_number * $price;
			// echo $price_sum;
			//并以购物车自增id和商品id 修改商品总价
			$ress=$Cart_Home->add_price_sum($goods_id,$cart_id,$price_sum);
			$result=$Cart_Home->getall($user_id);
			$goods_sums = array_sum(array_column($result,'goods_sum_price'));
			// echo $goods_sums;
			if ($res && $ress) {
				echo json_encode($goods_sums);
			}
		}
	}
	/**
	 * 确认订单
	 */
	public function confirm(){
		if(Session::has('user_id') && Session::has('user_name')){
			$user_id = session::get('user_id');
			$Cart_Home= new \App\Cart_Home();
			$Member_Home= new \App\Member_Home();
			$Pay_Home= new \App\Pay_Home();
			$res=$Cart_Home->lists($user_id);
			$address=$Member_Home->selectss($user_id);
			$address_check=$Member_Home->getChecked($user_id);
			$pay_res=$Pay_Home->lists();
			$sum=$this->goods_price+= array_sum(array_column($res,'goods_sum_price'));
			return view('Home/buycar_two',['res'=>$res,'sum'=>$sum,'address'=>$address,'address_check'=>$address_check,'pay_res'=>$pay_res]);

		// }else{
			echo '<script>alert("您还没登录,请先登录！！！");window.location.href="/home/login"</script>';
		}
	}
	/**
	 * //订单页面收货地址查询
	 */
	public function getAddress($address_id){
		$Member_Home= new \App\Member_Home();
		$address=$Member_Home->getOne($address_id);
		// print_r($address);
		if($address){
			echo json_encode($address[0]);
		}else{
			echo -1;
		}
	}
	/**
	 * 生成订单
	 */
	public function setOrder($address_id,$pay_id){
		//取出购物车数据
		$user_id = session::get('user_id');
		$Cart_Home= new \App\Cart_Home();
		$res=$Cart_Home->lists($user_id);
		echo "<pre>";
        print_r($res);
		// $this->checkNumberAndPrice($res);
		// //组装订单信息
		// $this->addOrder($address_id,$pay_id);
	}
	/**
	 * [组装订单信息]
	 * @param [type] $address_id [收货地址id]
	 * @param [type] $pay_id     [支付方式]
	 */
	public function addOrder($address_id,$pay_id){
		$Pay_Home= new \App\Pay_Home();
		$Member_Home= new \App\Member_Home();
		$Cart_Home= new \App\Cart_Home();
		$Order_Home= new \App\Order_Home();
		$user_id = session::get('user_id');
		$pay_res=$Pay_Home->select_field($pay_id);
		$pay_res=$pay_res[0];    
		$address_res=$Member_Home->getOnes($address_id,$user_id);
		$address_res=$address_res[0]; 
		$result=$Cart_Home->getall($user_id);
		$goods_price = array_sum(array_column($result,'goods_sum_price'));
		$order = array_merge($address_res, $pay_res);
		$order['order_sn'] = "NBOR_" . date('YmdHis') . rand(1000, 9999);
        $order['goods_price'] = $goods_price;
        $order['order_price'] = $goods_price;
        $order['add_time'] = time();
        $order['confirm_time'] = time();
        // echo "<pre>";
        // print_r($order);die;
        $order_res=$Order_Home->add($order);
        if($order_res){
        	echo 1;
        }else{
        	echo -2;
        }


	}
	/**
	 * 验证购物车库存和价格
	 * @return [type] [description]
	 */
	public function checkNumberAndPrice($goods=array()){
		$Product= new \App\Product();
		foreach ($goods as $key => $value) {
			$goods_id=$value['goods_id'];
			$product_attr=$value['product_attr_id'];
			$product_number=$value['buy_num'];
			$check_Num=$Product->checkedNum($goods_id,$product_attr,$product_number);
		}
		if(!$check_Num){
			echo -1;
		}
	}

	public function buycar_three(){
		return view('Home/buycar_three');
	}
}

 ?>